const express = require('express')
const router = express.Router()
const { enCrypt, deCode } = require('../utils/crypto')
const jsonwebtoken = require('../utils/jsonwebtoken')
const { Success, Error } = require('../utils/baseModel')
const { getUser, saveUser } = require('../db/dbUser')
//注册
router.post('/register', async (req, res, next) => {
    try {
        const { username, password } = req.body
        const _getUser = await getUser()
        const userVerification = _getUser.account.every(item => item.username !== username)
        if (userVerification) {
            // let passwordCode = password
            // passwordCode = enCrypt(passwordCode)
            const _id = _getUser.account.length
            _getUser.account.push({
                id: _id ? _id : 0,
                username: username,
                password: password
            })
            console.log(_getUser)
            await saveUser(_getUser)
            res.send(new Success({ message: '注册成功' }))
            return
        }
        res.send(new Error({ message: '账号已存在' }))
    } catch (error) {
        res.send(new Error({ message: error }))
    }
})
//登录
router.post('/login', async (req, res, next) => {
    try {
        const { username, password } = req.body
        const _getUser = await getUser()
        const userVerification = _getUser.account.some(item => item.username === username && item.password === password)
        if (userVerification) {
            const returnToken = await jsonwebtoken.getToken(req.body)
            res.send(new Success({ token: returnToken }))
            return
        }
        res.send(new Error({ message: '密码错误' }))
    } catch (error) {
        res.send(new Error({ message: error }))
    }
})

//注销
router.delete('/logout', async (req, res, next) => {
    try {
        const { username, password } = req.body
        const _getUser = await getUser()
        const index = _getUser.account.findIndex(item => item.username === username && item.password === (password))
        if (index === -1) {
            return res.status(404).json({ msg: "未找到删除项" })
        }
        _getUser.account.splice(index, 1)
        await saveUser(_getUser)
        res.send(new Success({ msg: "删除成功" }))
    } catch (error) {
        res.send(new Error({ message: error }))
    }
})

//修改密码
router.patch('/modification', async (req, res, next) => {
    try {
        const { username, password, changePassword } = req.body
        const _getUser = await getUser()
        const index = _getUser.account.findIndex(item => item.username === username && item.password === (password))
        if (index === -1) {
            return res.send(new Error({ message: '未找到修改账号' }))
        }
        _getUser.account[index].password = changePassword
        await saveUser(_getUser)
        res.send(new Success({ msg: "修改成功" }))
    } catch (error) {
        res.send(new Error({ message: error }))
    }
})
module.exports = router